package com.dormitory.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dormitory.manage.pojo.User;
import com.dormitory.manage.result.Result;
import com.dormitory.manage.service.UserService;
import com.dormitory.manage.utils.CreateVerifiCodeImage;
import com.dormitory.manage.utils.TokenUtil;
import com.dormitory.manage.vo.LoginVo;
import com.dormitory.manage.vo.UpdateInfoVo;
import com.dormitory.manage.vo.UpdatePasswordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @description 系统控制层
 * @date 2023/4/5 0005 13:45
 */
@RestController
@RequestMapping("sys")
@CrossOrigin
@Slf4j
public class SystemController {
    @Resource
    private UserService userService;

    /**
    * @description 根据用户名获取用户
    * @param username
    * @returnType com.demo.result.Result
    * @author Administrator
    * @date  14:28
    */
    @GetMapping("user/getUserByUsername/{username}")
    public Result getUserByUsername(@PathVariable String username){
        User user = userService.getUserByUsername(username);
        return Result.ok(user);
    }

    /**
    * @description 用户登录
    * @param loginVo
    * @returnType com.demo.result.Result
    * @author Administrator
    * @date  14:28
    */
    @PostMapping("user/login")
    public Result userLogin(@RequestBody LoginVo loginVo){
        if (!this.verifiCode.equalsIgnoreCase(loginVo.getVerifiCode())){
            return Result.fail().message("验证码错误！");
        }
        boolean result = userService.login(loginVo);
        String token = TokenUtil.token(loginVo.getUsername(), loginVo.getUsername());
        if (result){
            userService.setToken(loginVo.getUsername(),token);
            return Result.ok(token);
        }else {
            User userByUsername = this.userService.getUserByUsername(loginVo.getUsername());
            if (userByUsername.getIsOnline() == 1){
                return Result.fail().message("该用户已在其他地方登录！");
            }
        }
        return Result.fail().message("用户名、密码或身份错误！");
    }

    /**
    * @description 根据token获取用户信息
    * @param token
    * @returnType com.demo.result.Result
    * @author Administrator
    * @date  15:24
    */
    @GetMapping("user/info")
    public Result getUserInfo(@RequestParam String token){
        User user = userService.getUserInfoByToken(token);
        user.setPassword(null);
        return Result.ok(user);
    }

    @GetMapping("user/logout")
    public Result logout(@RequestParam String token){
        boolean result = userService.logout(token);
        if (result){
            return Result.ok("用户已退出！");
        }
        return Result.fail();
    }
    private String verifiCode;
    @GetMapping("user/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //获取验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取验证码字符串
        String verifiCode = String.valueOf(CreateVerifiCodeImage.getVerifiCode());
        //将验证码放入当前请求域中
//        request.getSession().setAttribute("verifiCode",verifiCode);
        this.verifiCode = verifiCode;
//        this.verifiCode = verifiCode;
        try {
            //将验证码图片通过输出流做出响应
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
    * @description 修改密码
    * @param updatePasswordVo
    * @returnType com.dormitory.manage.result.Result
    * @author Administrator
    * @date  16:52
    */
    @PostMapping("updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordVo updatePasswordVo){
        boolean result = userService.updatePassword(updatePasswordVo);
        if (result){
            return Result.ok();
        }
        return Result.fail().message("原密码错误，请重试！");
    }

    /**
    * @description 更新用户信息
    * @param updateInfoVo
    * @returnType com.dormitory.manage.result.Result
    * @author Administrator
    * @date  16:04
    */
    @PostMapping("updateInfo/{username}")
    public Result updateInfo(@PathVariable String username,@RequestBody UpdateInfoVo updateInfoVo){
        boolean result = userService.updateInfo(username,updateInfoVo);
        if (result){
            return Result.ok();
        }
        return Result.fail().message("更新失败，请重试！");
    }

    @GetMapping("getUsers")
    public Result getUsers(){
        Long users = this.userService.getBaseMapper().selectCount(null);
        return Result.ok(users);
    }

    @GetMapping("getAccesses")
    public Result getAccesses(){
        List<User> users = this.userService.getBaseMapper().selectList(null);
        Integer accesses = 0;
        for (User u: users) {
            accesses += u.getAccesses();
        }
        return Result.ok(accesses);
    }
}
